﻿using System.Web;
using Orchard.Localization;
using Orchard.Messaging.Events;
using Orchard.Messaging.Models;
using Orchard.ContentManagement;

namespace Contrib.CommentNotifications.Handlers {
    public class UserMessagesAlteration : IMessageEventHandler {
        private readonly IContentManager _contentManager;

        public UserMessagesAlteration(IContentManager contentManager) {
            _contentManager = contentManager;
            T = NullLocalizer.Instance;
        }

        public Localizer T { get; set; }

        public void Sending(MessageContext context) {
            if (context.MessagePrepared)
                return;

            var contentItem = _contentManager.Get(context.Recipient.Id);
            if ( contentItem == null )
                return;

            var recipient = ((dynamic)contentItem).UserPart;
            if ( recipient == null )
                return;

            switch (context.Type) {
                case CommentPartHandler.CommentCreated:
                    context.MailMessage.Subject = T("New Comment").Text;
                    context.MailMessage.Body =
                        T("The user <b>{0}</b> with email {1} has created a new comment on <a href=\"{2}\">{3}</a> <br/>Status: {4}<br/>Comment text: <br/> {5}",
                            HttpUtility.HtmlEncode(context.Properties["Author"]), 
                            HttpUtility.HtmlEncode(context.Properties["Email"]), 
                            context.Properties["DisplayUrl"],
                            HttpUtility.HtmlEncode(context.Properties["Title"]),
                            HttpUtility.HtmlEncode(context.Properties["Status"]),
                            HttpUtility.HtmlEncode(context.Properties["CommentText"])).Text;
                    FormatEmailBody(context);
                    context.MessagePrepared = true;
                    break;
            }
        }

        private static void FormatEmailBody(MessageContext context) {
            context.MailMessage.Body = "<p style=\"font-family:Arial, Helvetica; font-size:10pt;\">" + context.MailMessage.Body;
            context.MailMessage.Body += "</p>";
        }

        public void Sent(MessageContext context) {
        }
    }
}
